#include <iostream>
#include <fstream>
#include <sstream>
#include <cstring>

using namespace std;


struct structByteAlign
{
    char    s_c;
    int     s_i;
    double  s_d;
    float   s_f;
};

// write data in memory to bin file using write()
void test()
{
    std::ofstream ofs;
    ofs.open("structByteAlign.bin", std::ios::out | std::ios::binary | std::ios::trunc);
    structByteAlign mystruct = {
        .s_c = 48,
        .s_i = 3,
        .s_d = 4,
        .s_f = 5 };

    std::cout << "sizeof char is : " << sizeof(char) << endl;
    std::cout << "sizeof int is : " << sizeof(int) << endl;
    std::cout << "sizeof double is : " << sizeof(double) << endl;
    std::cout << "sizeof float is : " << sizeof(float) << endl;
    std::cout << "sum sizeof is : " << sizeof(char) + sizeof(int) + sizeof(double) + sizeof(float) << endl;

    std::cout << "sizeof mystruct is : " << sizeof(mystruct)<< endl;
    const char * p = reinterpret_cast<const char*>(&mystruct);
    // ofs.write(p, sizeof mystruct);
    ofs << mystruct.s_c << " " << mystruct.s_i << " " << mystruct.s_d << " " << mystruct.s_f << endl;
    ofs.close();
}

// read data from bin file using read()  /  how to use rdbuf() to transfer a whole stream to another stream(stringstream) 
// both methods above get the same result when wtrto to structByteAlign01.bin
void test01()
{
    std::ifstream ifs;
    ifs.open("structByteAlign.bin", std::ios::in);

    int a = 0;
    string str;
    // ifs >> str;
    // std::getline(ifs, str);
    // cout << "a = " << a << endl;
    // cout << "str = " << str << endl;
    stringstream sstr;
    sstr << ifs.rdbuf();
    // sstr << '2' << endl;
    str = sstr.str();
    cout << "sstr =" << str << endl;

    std::ofstream ofs;
    ofs.open("structByteAlign01.bin", ios::out | std::ios::binary | std::ios::trunc);

    const char* c = str.c_str();
    char* c1 = new char[300];
    ifs.seekg(0, ios::beg);
    ifs.read(c1, str.length());

    ofs.write(c1, str.length());
    ofs.write(c, str.length());

    delete c1;
    
    ofs.close();
    ifs.close();

}

int main()
{
    // test();
    test01();
    return 0;
}